<template>
  <a-modal
    v-model:open="visible"
    title="参与申报"
    class="participateModal"
    destroyOnClose
    :width="500"
    :maskClosable="false"
    @cancel="cancel"
    centered
  >
    <a-form
      :model="form"
      :rules="rules"
      ref="formRef"
      layout="inline"
      :labelCol="labelCol"
    >
      <a-form-item label="需求计划名称" name="planName">
        <a-input
          v-model:value="form.planName"
          class="formInput"
          placeholder="请输入"
          :disabled="true"
        />
      </a-form-item>

      <a-form-item label="最大日备用容量(kW)" name="maxDailyCapacity">
        <a-input-number
          v-model:value="form.maxDailyCapacity"
          class="formInput"
          placeholder="10000"
          :min="0"
          :disabled="true"
        />
      </a-form-item>

      <!-- <a-form-item label="选择备用用户" name="selectedUsers">
        <a-select
          v-model:value="form.selectedUsers"
          class="formInput"
          placeholder="请选择"
          mode="multiple"
          allow-clear
          show-search
          optionFilterProp="label"
        >
          <a-select-option
            v-for="item in userList"
            :value="item.id"
            :key="item.id"
            :label="item.name"
          >
            {{ item.name }}
          </a-select-option>
        </a-select>
      </a-form-item> -->

      <a-form-item label="用户资源清单" name="fileList">
        <div class="upload-container">
          <a-upload
            v-model:file-list="form.fileList"
            :before-upload="beforeUpload"
            :maxCount="1"
            accept=".xlsx,.xls,.csv"
            :action="uploadUrl"
            :headers="headers"
            @change="handleUploadChange"
          >
            <a-button
              class="greenpPlainBtn"
              :loading="importLoading"
              size="small"
            >
              <UploadOutlined />
              选择文件
            </a-button>
            <a-button
              type="link"
              @click.stop="handleDownloadTemplate"
              class="downLoadTep"
              >下载模板</a-button
            >
            <template #itemRender="{ file }">
              <div class="ant-upload-list-item-info">
                <span class="ant-upload-list-item-name">{{ file.name }}</span>
              </div>
            </template>
          </a-upload>
        </div>
        <!--  <div class="upload-section">
          <a-button type="primary" ghost @click="handleUpload">
            点击上传
          </a-button>
          <a-button type="link" @click="handleDownloadTemplate">
            下载模板
          </a-button>
        </div> -->
      </a-form-item>
    </a-form>

    <template #footer>
      <div class="footerBar">
        <a-button key="back" @click="cancel">取消</a-button>
        <a-button
          key="submit"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
        >
          提交
        </a-button>
      </div>
    </template>
  </a-modal>
</template>

<script setup>
import { ref, reactive, watch, inject } from "vue"
import { message } from "ant-design-vue"
import storage from "@/utils/storage"
const userInf = storage.getItem("USER_INFO")
const headers = ref({
  Authorization: "Bearer " + userInf.access_token,
})
const $api = inject("$api")
const labelCol = { style: { width: "155px" } }
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  recordData: {
    type: Object,
    default: () => ({}),
  },
})

const emits = defineEmits(["update:visible", "refresh"])

const visible = ref(props.visible)
const loading = ref(false)
const importLoading = ref(false)
const formRef = ref(null)

// 表单数据
const form = reactive({
  planName: "",
  maxDailyCapacity: null,
  selectedUsers: [],
  fileList: [],
})

// 用户列表数据（模拟）
const userList = ref([
  { id: 1, name: "用户A" },
  { id: 2, name: "用户B" },
  { id: 3, name: "用户C" },
  { id: 4, name: "用户D" },
])

// 表单验证规则
const rules = {
  planName: [
    { required: true, message: "请输入需求计划名称", trigger: "blur" },
  ],
  maxDailyCapacity: [
    { required: true, message: "请输入最大日备用容量", trigger: "blur" },
  ],
  selectedUsers: [
    { required: true, message: "请选择备用用户", trigger: "change" },
  ],
  fileList: [
    { required: true, message: "请上传用户资源清单", trigger: "change" },
  ],
}

// 监听visible变化
watch(
  () => props.visible,
  (val) => {
    visible.value = val
    if (val && props.recordData) {
      // 根据传入的记录数据初始化表单
      form.planName = props.recordData.planName
      form.maxDailyCapacity = props.recordData.monthlyDemandCapacity
    }
  }
)

watch(visible, (val) => {
  emits("update:visible", val)
})

// 取消
const cancel = () => {
  visible.value = false
  formRef.value?.clearValidate()
  // 重置表单
  Object.assign(form, {
    planName: "",
    maxDailyCapacity: null,
    selectedUsers: [],
    fileList: [],
  })
}

// 提交
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    loading.value = true

    const params = {
      ...form,
      recordId: props.recordData?.id,
    }

    // 这里调用实际的API
    // const res = await $api.participateDeclaration(params)

    // 模拟API调用
    await new Promise((resolve) => setTimeout(resolve, 1000))

    message.success("申报成功")
    cancel()
    emits("refresh")
  } catch (error) {
    console.error("申报失败:", error)
  } finally {
    loading.value = false
  }
}

// 上传文件
const handleUpload = () => {
  // 这里实现文件上传逻辑
  message.info("上传功能待实现")
}
const uploadUrl = ref(`${$api.uploadAction().url}`)
/* const uploadUrl = async (val) => {
  return `${$api.uploadAction().url}`
} */
// 文件上传前的处理
const beforeUpload = (file) => {
  importLoading.value = true
  const isValidFormat =
    file.type ===
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
    file.type === "application/vnd.ms-excel" ||
    file.name.endsWith(".csv")
  if (!isValidFormat) {
    message.error("只支持上传 .xlsx, .xls, .csv 格式的文件！")
    return false
  }
}

// 文件上传变化处理
const handleUploadChange = (data) => {
  importLoading.value = false
  form.fileList = data.fileList
}

// 下载模板
const handleDownloadTemplate = (event) => {
  event.preventDefault()
  event.stopPropagation()
  //模板下载
}
</script>

<style lang="less" scoped>
.formInput {
  width: 250px;
}

/* .upload-container {
  display: flex;
  align-items: center;
  gap: 12px;
}

.upload-section {
  display: flex;
  gap: 12px;
  align-items: center;
} */

.footerBar {
  text-align: center;
  margin-top: 20px;
}

:deep(.ant-form-item) {
  margin-bottom: 20px;
}

:deep(.ant-modal-header) {
  background: #1f1f1f;
  border-bottom: 1px solid #303030;
}

:deep(.ant-modal-content) {
  background: #1f1f1f;
  color: #fff;
}

:deep(.ant-modal-footer) {
  background: #1f1f1f;
  border-top: 1px solid #303030;
}
.downLoadTep {
  padding: 4px 5px 4px 10px;
}
</style>
